﻿using AutoMapper;
using B.S.BaseData.Domain.Entities;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.Write.API.Command.RoleCommand;
using MediatR;

namespace B.S.BaseData.Write.API.CommandHandler.RoleHandler
{
    public class CreateRoleHandler : IRequestHandler<CreateRoleCommand, APIResult<object>>
    {
        private readonly IBaseRepository<Role> roleRep;
        private readonly IMapper mapper;

        public CreateRoleHandler(IBaseRepository<Role> roleRep,IMapper mapper)
        {
            this.roleRep = roleRep;
            this.mapper = mapper;
        }
        public async Task<APIResult<object>> Handle(CreateRoleCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            var roleName = roleRep.GetAll().Where(x=>x.RoleName==request.RoleName);
            if (roleName.Count()>0)
            {
                result.Code = APIEnum.Failed;
                result.Msg = "角色名称有重复,不能添加";
                return await Task.FromResult(result);
            }
          
                var role = mapper.Map<Role>(request);
                role.CreateTime = DateTime.Now;
                role.CreateUser = "张三";
                role.UpdateUser = "";
                role.IsDeleted = false;
                roleRep.Add(role);
                result.Code = APIEnum.Success;
                result.Msg = "添加角色信息成功";
                return await Task.FromResult(result);

           
        }
    }
}
